package com.atguigu.lease.common.Interceptor;

import com.atguigu.lease.common.context.BaseContext;
import com.atguigu.lease.common.globalException.LeaseException;
import com.atguigu.lease.common.properties.JwtProperties;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.concurrent.TimeUnit;

@Component
public class JwtTokenAppInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }

        String appTokenName = jwtProperties.getAppTokenName();
        String token = request.getHeader(appTokenName);


        if (token == null){
            //获取不到token,则抛出未登录异常
            throw new LeaseException(ResultCodeEnum.ADMIN_LOGIN_AUTH);
        }
        Claims claims = JwtUtil.parseJwt(jwtProperties.getAppSecretKey(), token);
        if (claims == null){
            //解析失败，则抛出无权限异常
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCESS_FORBIDDEN);
        }
        //获取登录用户id
        Long userId = Long.valueOf(claims.get("appUserId").toString());
        //将用户登录id存入reids中
        redisTemplate.opsForValue().set("appUserId",userId,3600, TimeUnit.SECONDS);
        //解析正确，则放行
        return true;
    }
}
